/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.cloudfarming.client.messaging;

import java.util.Date;
import java.util.logging.Logger;
import nl.cloudfarming.eventbus.BaseGuiEventProducer;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.netbeans.api.settings.ConvertAsProperties;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//nl.cloudfarming.client.messaging//TestWindow//EN",
autostore = false)
public final class TestWindowTopComponent extends TopComponent {

    private static TestWindowTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    private static final String PREFERRED_ID = "TestWindowTopComponent";
    private final MessageEventProducer messageEventProducer = new MessageEventProducer(); 

    private static int COUNTER = 0;
    
    public TestWindowTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(TestWindowTopComponent.class, "CTL_TestWindowTopComponent"));
        setToolTipText(NbBundle.getMessage(TestWindowTopComponent.class, "HINT_TestWindowTopComponent"));
//        setIcon(ImageUtilities.loadImage(ICON_PATH, true));

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(TestWindowTopComponent.class, "TestWindowTopComponent.jButton1.text")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(TestWindowTopComponent.class, "TestWindowTopComponent.jLabel1.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(97, 97, 97)
                        .addComponent(jButton1)))
                .addContainerGap(16, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel1)
                .addGap(51, 51, 51)
                .addComponent(jButton1)
                .addContainerGap(184, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

     
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Message message  = new Message();
        message.setOrigin("Afzender " + (COUNTER));
        message.setTitle("Titel" + (COUNTER));
        message.setMessageText("[MessageText " + (COUNTER++) + "] - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam risus nisl, dictum vel viverra et, egestas vitae nulla. Cras eu tortor sit amet dui cursus accumsan non eu purus. Etiam fringilla, nisl id euismod auctor, augue nulla facilisis libero, a vulputate diam nisi vulputate libero. Cras eu velit mi. Fusce ut purus ut augue gravida malesuada. Ut placerat rutrum convallis. Donec feugiat suscipit mauris, eu hendrerit tortor bibendum quis. Nulla aliquet turpis at quam viverra venenatis. Sed ac suscipit massa. Nam fringilla leo eu elit mattis vestibulum. Mauris auctor, nulla in eleifend ultricies, magna ligula condimentum tortor, hendrerit mattis risus lectus id justo. Vivamus tristique hendrerit dui, ac dapibus nunc blandit elementum.\n\nAliquam erat volutpat. Nullam a arcu eget lectus dignissim elementum sed id ante. Nam quis nulla a nunc pellentesque malesuada non a dui. Vivamus porttitor suscipit tincidunt. Nulla id diam augue. Pellentesque lobortis nibh in odio lacinia sollicitudin. Quisque semper rhoncus placerat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer eget orci mi. Ut et nibh at velit porttitor dictum. In placerat arcu sed erat luctus ac venenatis lectus semper. Nulla ut mi augue, a ultrices leo. Proin rutrum volutpat nibh, in malesuada leo convallis vel. Praesent lacinia magna venenatis nibh posuere nec gravida risus molestie. Donec est mi, viverra quis aliquam vitae, commodo hendrerit tortor.");
        message.setDateReceived(new Date());
        message.setTransientMessage(false);
        //MessagePopUp mpp = new MessagePopUp(message);
        //mpp.setVisible(true);*/
        
        messageEventProducer.triggerEvent(new MessageEvent(message, MessageEventKey.NEW_MESSAGE));
                        
        /*File file = new File(".");
        String blaat = "";
        try {
            blaat = file.getCanonicalPath().toString();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        Notification n = (Notification) NotificationDisplayer.getDefault().notify("titeltje", new ImageIcon("question_mark.jpg"), "Message", null);
        */
    }//GEN-LAST:event_jButton1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized TestWindowTopComponent getDefault() {
        if (instance == null) {
            instance = new TestWindowTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the TestWindowTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized TestWindowTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(TestWindowTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof TestWindowTopComponent) {
            return (TestWindowTopComponent) win;
        }
        Logger.getLogger(TestWindowTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }


    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
    }

    Object readProperties(java.util.Properties p) {
        if (instance == null) {
            instance = this;
        }
        instance.readPropertiesImpl(p);
        return instance;
    }

    private void readPropertiesImpl(java.util.Properties p) {
        String version = p.getProperty("version");
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }
    
    private class MessageEventProducer extends BaseGuiEventProducer{

        public MessageEventProducer() {
            super(MessageEventKey.class);
        }

    }
}
